package com.example.color_test.test;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.util.concurrent.Callable;

public class CalculateTask implements Callable<Long>{

    // 横纵坐标起始点
    public int startX;
    public int startY;

    // 横纵坐标终点
    public int endX;
    public int endY;

    // 持有BufferedImage引用
    public BufferedImage bi;

    public int redRange = 0;
    public int greenRange = 0;
    public int blueRange = 0;

    // 使用构造函数传参
    public CalculateTask(int sx,int sy,int ex,int ey,BufferedImage bImage) {
        startX = sx;
        startY = sy;
        endX = ex;
        endY = ey;
        bi = bImage;
    }

    // 使用构造函数传参
    public CalculateTask(int sx,int sy,int ex,int ey,BufferedImage bImage,int _R,int _G ,int _B) {
        startX = sx;
        startY = sy;
        endX = ex;
        endY = ey;
        bi = bImage;
        redRange = _R;
        greenRange = _G;
        blueRange = _B;
    }

    @Override
    public Long call() throws Exception {
        // 定义HSV空间
        float[] hsv = new float[3];

        long res = 0L;

        // 开始遍历分配给该线程的像素点
        for (int i = startX; i < endX; i++) {
            for (int j = startY; j < endY; j++) {

                // 当前像素点
                int pixel = bi.getRGB(i, j);

                // 获取RGB各值
                int R = (pixel & 0xff0000) >> 16;// R
                int G = (pixel & 0xff00) >> 8;// G
                int B = (pixel & 0xff);// B

                // rgb转hsv
                Color.RGBtoHSB(R, G, B, hsv);
                if(redRange!=0&&greenRange!=0&&blueRange!=0){
                    float[] _hsv = new float[3];
                    Color.RGBtoHSB(redRange, greenRange, blueRange, hsv);
                    if (hsv[2] == _hsv[2] && hsv[1] == _hsv[1] && hsv[0] == _hsv[0]) {
                        res++;
                    }
                }else if (hsv[2] >= 0.075 && hsv[1] >= 0.15 && hsv[0] > 0.1389 && hsv[0] <= 0.4444) {
                    //使用hsv判断该像素点是否可以判定为绿色像素点
                    res++;
                }

            }
        }
        System.out.println("当前线程:" + Thread.currentThread().getName() + ",绿色像素点个数：" + res);
        return res;
    }
}
